package gov.pbc.nn.core.el;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Map;

import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;

import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.dorado.core.el.ContextVarsInitializer;

public class PbcCoreContextVarsInitializer implements ContextVarsInitializer {

	@Override
	public void initializeContext(Map<String, Object> vars) throws Exception {

		vars.put("field", new FieldGetter());
	}

	public static class FieldGetter {

		public Object get(String classField) throws Exception {
			if (StringUtils.contains(classField, "#")) {
				String beanId = StringUtils.substringBefore(classField, "#");
				String fieldName = StringUtils.substringAfter(classField, "#");
				Object bean = ContextHolder.getApplicationContext().getBean(beanId);
				Field field = FieldUtils.getField(bean.getClass(), fieldName, true);
				if (Modifier.isStatic(field.getModifiers())) {
					return field.get(null);
				} else {
					return field.get(bean);
				}
			} else {
				String className = StringUtils.substringBeforeLast(classField, ".");
				String fieldName = StringUtils.substringAfterLast(classField, ".");
				Class<?> clazz = ClassUtils.getClass(className);
				
				Field field = FieldUtils.getField(clazz, fieldName, true);
				if (Modifier.isStatic(field.getModifiers())) {
					return field.get(null);
				} else {
					return null;
				}
			}
		}
	}

}
